<template>
  <div class="video-list-container">
    <div class="page-header">
      <h2>视频管理</h2>
      <a-button type="primary" class="add-button" @click="handleUpload">
        <template #icon>
          <PlusOutlined />
        </template>
        上传视频
      </a-button>
    </div>

    <!-- 搜索筛选区域 -->
    <a-card class="search-card">
      <a-form layout="inline" :model="searchForm" class="search-form">
        <a-form-item label="视频状态">
          <a-select 
            v-model:value="searchForm.status" 
            placeholder="请选择视频状态" 
            style="width: 150px;"
            allow-clear
          >
            <a-select-option value="pending">待审核</a-select-option>
            <a-select-option value="ai_reviewing">AI审核中</a-select-option>
            <a-select-option value="ai_approved">AI审核通过</a-select-option>
            <a-select-option value="ai_rejected">AI审核拒绝</a-select-option>
            <a-select-option value="manual_reviewing">人工审核中</a-select-option>
            <a-select-option value="approved">审核通过</a-select-option>
            <a-select-option value="rejected">审核拒绝</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item>
          <a-button type="primary" @click="handleSearch">
            <template #icon>
              <SearchOutlined />
            </template>
            搜索
          </a-button>
          <a-button style="margin-left: 8px;" @click="handleReset">
            重置
          </a-button>
        </a-form-item>
      </a-form>
    </a-card>

    <!-- 视频列表表格 -->
    <div class="table-container">
      <a-table 
        :columns="columns" 
        :data-source="videoList" 
        :loading="loading"
        :pagination="pagination"
        @change="handleTableChange"
        row-key="id"
        :scroll="{ x: 1400, y: 600 }"
        class="video-table"
      >
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'cover_image'">
          <img 
            :src="record.cover_image?.thumbnail_url || record.cover_image?.oss_url || '/placeholder-image.svg'" 
            alt="封面" 
            class="video-cover"
            @error="$event.target.src='/placeholder-image.svg'"
          />
        </template>
        <template v-else-if="column.key === 'status'">
          <a-tag :color="getStatusColor(record.status)" class="status-tag">
            {{ getStatusText(record) }}
          </a-tag>
        </template>
        <template v-else-if="column.key === 'ai_review_result'">
          <a-tag v-if="record.ai_review_result" :color="record.ai_review_result.is_approved ? 'green' : 'red'">
            {{ record.ai_review_result.is_approved ? '通过' : '未通过' }}
          </a-tag>
          <span v-else>-</span>
        </template>
        <template v-else-if="column.key === 'file_size'">
          {{ formatFileSize(record.file_size) }}
        </template>
        <template v-else-if="column.key === 'created_at'">
          {{ formatDate(record.created_at) }}
        </template>
        <template v-else-if="column.key === 'action'">
          <a-space class="action-buttons">
            <a-button type="link" size="small" @click="handleEdit(record)">
              编辑
            </a-button>
            <a-button type="link" size="small" @click="handleView(record)">
              查看
            </a-button>
            <a-button 
              v-if="record.status === 'manual_reviewing'" 
              type="link" 
              size="small" 
              @click="handleReview(record)"
            >
              审核
            </a-button>
            <a-button 
              v-if="record.status === 'approved' && !record.is_active" 
              type="link" 
              size="small" 
              @click="handlePublish(record)"
            >
              发布
            </a-button>
            <a-button 
              v-if="record.status === 'approved' && record.is_active" 
              type="link" 
              size="small" 
              @click="handleUnpublish(record)"
            >
              下架
            </a-button>
            <a-popconfirm
              title="确定要删除这个视频吗？"
              @confirm="handleDelete(record.id)"
            >
              <a-button type="link" size="small" danger>
                删除
              </a-button>
            </a-popconfirm>
          </a-space>
        </template>
      </template>
      </a-table>
    </div>
    
    <!-- 视频详情弹窗 -->
     <a-modal
       :open="detailModalVisible"
       title="视频详情"
       width="1000px"
       :footer="null"
       @cancel="handleDetailModalClose"
       cancel-text="关闭"
     >
       <a-spin :spinning="detailLoading">
         <div class="video-detail-content" v-if="videoDetail">
           <!-- 媒体预览 -->
           <div class="detail-section">
             <h4 class="section-title">媒体预览</h4>
             <div class="media-preview">
               <!-- 封面图片 -->
               <div class="media-item" v-if="videoDetail.cover_image?.oss_url">
                 <h5 class="media-title">封面图片</h5>
                 <img 
                   :src="videoDetail.cover_image.oss_url" 
                   alt="视频封面" 
                   class="cover-preview"
                   @error="$event.target.src='/placeholder-image.svg'"
                 />
               </div>
               
               <!-- 视频文件 -->
               <div class="media-item" v-if="videoDetail.file?.oss_url">
                 <h5 class="media-title">视频文件</h5>
                 <video 
                   :src="videoDetail.file.oss_url" 
                   controls 
                   class="video-preview"
                   preload="metadata"
                 >
                   您的浏览器不支持视频播放。
                 </video>
               </div>
             </div>
           </div>
           
           <!-- 基本信息 -->
           <div class="detail-section">
             <h4 class="section-title">基本信息</h4>
             <div class="detail-grid">
               <div class="detail-item">
                 <span class="label">ID:</span>
                 <span class="value">{{ videoDetail.id || '-' }}</span>
               </div>
               <div class="detail-item">
                 <span class="label">文件ID:</span>
                 <span class="value">{{ videoDetail.file_id || '-' }}</span>
               </div>
               <div class="detail-item">
                 <span class="label">标题:</span>
                 <span class="value">{{ videoDetail.title || '-' }}</span>
               </div>
               <div class="detail-item">
                 <span class="label">描述:</span>
                 <span class="value">{{ videoDetail.description || '-' }}</span>
               </div>
               <div class="detail-item">
                 <span class="label">状态:</span>
                 <span class="value">{{ getStatusText(videoDetail) }}</span>
               </div>
               <div class="detail-item">
                 <span class="label">上传来源:</span>
                 <span class="value">{{ videoDetail.upload_source || '-' }}</span>
               </div>
             </div>
           </div>

           <!-- 文件信息 -->
           <div class="detail-section">
             <h4 class="section-title">文件信息</h4>
             <div class="detail-grid">
               <div class="detail-item">
                 <span class="label">文件大小:</span>
                 <span class="value">{{ formatFileSize(videoDetail.file_size) }}</span>
               </div>
               <div class="detail-item">
                 <span class="label">时长:</span>
                 <span class="value">{{ formatDuration(videoDetail.duration) }}</span>
               </div>
               <div class="detail-item">
                 <span class="label">分辨率:</span>
                 <span class="value">{{ videoDetail.resolution || '-' }}</span>
               </div>
               <div class="detail-item">
                 <span class="label">封面图片ID:</span>
                 <span class="value">{{ videoDetail.cover_image_id || '-' }}</span>
               </div>
             </div>
           </div>

           <!-- 统计信息 -->
           <div class="detail-section">
             <h4 class="section-title">统计信息</h4>
             <div class="detail-grid">
               <div class="detail-item">
                 <span class="label">观看次数:</span>
                 <span class="value">{{ videoDetail.view_count || 0 }}</span>
               </div>
               <div class="detail-item">
                 <span class="label">点赞次数:</span>
                 <span class="value">{{ videoDetail.like_count || 0 }}</span>
               </div>
               <div class="detail-item">
                 <span class="label">是否精选:</span>
                 <span class="value">{{ videoDetail.is_featured ? '是' : '否' }}</span>
               </div>
               <div class="detail-item">
                 <span class="label">是否激活:</span>
                 <span class="value">{{ videoDetail.is_active ? '是' : '否' }}</span>
               </div>
             </div>
           </div>

           <!-- 作者信息 -->
           <div class="detail-section">
             <h4 class="section-title">作者信息</h4>
             <div class="detail-grid">
               <div class="detail-item">
                 <span class="label">作者昵称:</span>
                 <span class="value">{{ videoDetail.author_nickname || '-' }}</span>
               </div>
               <div class="detail-item">
                 <span class="label">作者头像ID:</span>
                 <span class="value">{{ videoDetail.author_avatar_id || '-' }}</span>
               </div>
             </div>
           </div>

           <!-- 时间信息 -->
           <div class="detail-section">
             <h4 class="section-title">时间信息</h4>
             <div class="detail-grid">
               <div class="detail-item">
                 <span class="label">创建时间:</span>
                 <span class="value">{{ formatDate(videoDetail.created_at) }}</span>
               </div>
               <div class="detail-item">
                 <span class="label">更新时间:</span>
                 <span class="value">{{ formatDate(videoDetail.updated_at) }}</span>
               </div>
               <div class="detail-item">
                 <span class="label">发布时间:</span>
                 <span class="value">{{ formatDate(videoDetail.published_at) }}</span>
               </div>
               <div class="detail-item">
                 <span class="label">拒绝原因:</span>
                 <span class="value">{{ videoDetail.reject_reason || '-' }}</span>
               </div>
             </div>
           </div>

           <!-- AI审核信息 -->
           <div class="detail-section" v-if="videoDetail.ai_review_result">
             <h4 class="section-title">AI审核信息</h4>
             <div class="detail-grid">
               <div class="detail-item">
                 <span class="label">审核结果:</span>
                 <span class="value">{{ videoDetail.ai_review_result.is_approved ? '通过' : '未通过' }}</span>
               </div>
               <div class="detail-item">
                 <span class="label">审核状态:</span>
                 <span class="value">{{ videoDetail.ai_review_result.status || '-' }}</span>
               </div>
               <div class="detail-item">
                 <span class="label">置信度:</span>
                 <span class="value">{{ videoDetail.ai_review_result.confidence ? `${videoDetail.ai_review_result.confidence}%` : '-' }}</span>
               </div>
               <div class="detail-item">
                 <span class="label">审核时间:</span>
                 <span class="value">{{ videoDetail.ai_review_result.review_time || '-' }}</span>
               </div>
             </div>
             
             <!-- AI审核详细结果 -->
             <div v-if="videoDetail.ai_review_result.audit_result" class="audit-details">
               <h5 class="subsection-title">详细审核结果</h5>
               <div class="detail-grid">
                 <div class="detail-item" v-if="videoDetail.ai_review_result.audit_result.Porn">
                   <span class="label">色情检测:</span>
                   <span class="value">{{ videoDetail.ai_review_result.audit_result.Porn.Suggestion }} ({{ videoDetail.ai_review_result.audit_result.Porn.Confidence }}%)</span>
                 </div>
                 <div class="detail-item" v-if="videoDetail.ai_review_result.audit_result.Terrorism">
                   <span class="label">暴恐检测:</span>
                   <span class="value">{{ videoDetail.ai_review_result.audit_result.Terrorism.Suggestion }} ({{ videoDetail.ai_review_result.audit_result.Terrorism.Confidence }}%)</span>
                 </div>
                 <div class="detail-item" v-if="videoDetail.ai_review_result.audit_result.Politics">
                   <span class="label">政治检测:</span>
                   <span class="value">{{ videoDetail.ai_review_result.audit_result.Politics.Suggestion }} ({{ videoDetail.ai_review_result.audit_result.Politics.Confidence }}%)</span>
                 </div>
                 <div class="detail-item" v-if="videoDetail.ai_review_result.audit_result.Ad">
                   <span class="label">广告检测:</span>
                   <span class="value">{{ videoDetail.ai_review_result.audit_result.Ad.Suggestion }} ({{ videoDetail.ai_review_result.audit_result.Ad.Confidence }}%)</span>
                 </div>
               </div>
             </div>
             
             <!-- AI拒绝原因 -->
             <div v-if="videoDetail.ai_review_result.reject_reasons && videoDetail.ai_review_result.reject_reasons.length > 0" class="reject-reasons">
               <h5 class="subsection-title">拒绝原因</h5>
               <div class="detail-item full-width">
                 <span class="value">{{ videoDetail.ai_review_result.reject_reasons.join(', ') }}</span>
               </div>
             </div>
           </div>
         </div>
       </a-spin>
     </a-modal>

     <!-- 编辑视频模态框 -->
     <a-modal
         :open="editModalVisible"
         title="编辑视频"
         width="600px"
         @ok="handleEditSubmit"
         @cancel="handleEditCancel"
         :confirm-loading="editLoading"
         ok-text="确认修改"
         cancel-text="取消"
       >
       <a-form
           :model="editForm"
           :label-col="{ span: 6 }"
           :wrapper-col="{ span: 18 }"
           layout="horizontal"
         >
         <a-form-item label="视频标题" name="title">
           <a-input v-model:value="editForm.title" placeholder="请输入视频标题" />
         </a-form-item>
         
         <a-form-item label="视频描述" name="description">
           <a-textarea 
             v-model:value="editForm.description"
             placeholder="请输入视频描述"
             :rows="4"
           />
         </a-form-item>
         
         <a-form-item label="上传来源" name="upload_source">
           <a-select v-model:value="editForm.upload_source" placeholder="请选择上传来源">
             <a-select-option value="admin">管理员上传</a-select-option>
             <a-select-option value="user">用户上传</a-select-option>
           </a-select>
         </a-form-item>
         
         <a-form-item label="封面图片" name="cover_file">
           <div v-if="editForm.current_cover_url" style="margin-bottom: 8px;">
             <img :src="editForm.current_cover_url" alt="当前封面" style="width: 100px; height: 60px; object-fit: cover; border-radius: 4px;" />
             <div style="font-size: 12px; color: #666; margin-top: 4px;">当前封面</div>
           </div>
           <a-upload
             :file-list="[]"
             :before-upload="() => false"
             @change="handleEditCoverFileChange"
             accept="image/*"
             :loading="editCoverFileUploading"
           >
             <a-button>
               <upload-outlined />
               选择新封面
             </a-button>
           </a-upload>
           <div style="font-size: 12px; color: #999; margin-top: 4px;">
             支持 JPG、PNG 格式，建议尺寸 16:9
           </div>
         </a-form-item>
       </a-form>
     </a-modal>

     <!-- 上传视频模态框 -->
     <a-modal
         :open="uploadModalVisible"
         title="上传视频"
         width="600px"
         @ok="handleUploadSubmit"
         @cancel="handleUploadCancel"
         :confirm-loading="uploadLoading"
         ok-text="确认上传"
         cancel-text="取消"
       >
       <a-form
           :model="uploadForm"
           :label-col="{ span: 6 }"
           :wrapper-col="{ span: 18 }"
           layout="horizontal"
         >
         <a-form-item label="视频标题" required>
           <a-input v-model:value="uploadForm.title" placeholder="请输入视频标题" />
         </a-form-item>
         
         <a-form-item label="视频描述">
           <a-textarea v-model:value="uploadForm.description" placeholder="请输入视频描述" :rows="4" />
         </a-form-item>
         
         <a-form-item label="上传来源">
           <a-select v-model:value="uploadForm.upload_source" placeholder="请选择上传来源">
             <a-select-option value="admin">管理员上传</a-select-option>
             <a-select-option value="user">用户上传</a-select-option>
           </a-select>
         </a-form-item>
         
         <a-form-item label="视频文件" required>
           <a-upload
             :file-list="[]"
             :before-upload="() => false"
             @change="handleVideoFileChange"
             accept="video/*"
             :loading="videoFileUploading"
           >
             <a-button>
               <upload-outlined />
               选择视频文件
             </a-button>
           </a-upload>
           <div v-if="uploadForm.video_file_name" style="margin-top: 8px; color: #52c41a;">
             已选择: {{ uploadForm.video_file_name }}
           </div>
         </a-form-item>
         
         <a-form-item label="封面图片">
           <a-upload
             :file-list="[]"
             :before-upload="() => false"
             @change="handleCoverFileChange"
             accept="image/*"
             :loading="coverFileUploading"
           >
             <a-button>
               <upload-outlined />
               选择封面图片
             </a-button>
           </a-upload>
           <div v-if="uploadForm.cover_file_name" style="margin-top: 8px; color: #52c41a;">
             已选择: {{ uploadForm.cover_file_name }}
           </div>
           <div style="font-size: 12px; color: #999; margin-top: 4px;">
             支持 JPG、PNG 格式，建议尺寸 16:9
           </div>
         </a-form-item>
       </a-form>
     </a-modal>

    <!-- 审核弹窗 -->
    <a-modal
      :open="reviewModalVisible"
      title="视频审核"
      width="600px"
      @ok="handleReviewSubmit"
      @cancel="handleReviewCancel"
      :confirm-loading="reviewLoading"
      ok-text="确认审核"
      cancel-text="取消"
    >
      <div v-if="currentReviewVideo">
        <div class="review-video-info">
          <h4>视频信息</h4>
          <p><strong>标题：</strong>{{ currentReviewVideo.title }}</p>
          <p><strong>描述：</strong>{{ currentReviewVideo.description }}</p>
          <p><strong>当前状态：</strong>{{ getStatusText(currentReviewVideo) }}</p>
        </div>
        
        <a-form :model="reviewForm" layout="vertical">
          <a-form-item label="审核状态" required>
            <a-select v-model:value="reviewForm.status" placeholder="请选择审核状态">
              <a-select-option value="approved">通过</a-select-option>
              <a-select-option value="rejected">拒绝</a-select-option>
            </a-select>
          </a-form-item>
          
          <a-form-item label="审核意见">
            <a-textarea v-model:value="reviewForm.reason" placeholder="请输入审核意见" :rows="4" />
          </a-form-item>
        </a-form>
      </div>
    </a-modal>
  </div>
</template>

<script>
import { defineComponent, ref, reactive, onMounted, computed } from 'vue'
import { message } from 'ant-design-vue'
import { PlusOutlined, SearchOutlined } from '@ant-design/icons-vue'
import { videoApi } from '@/api/video'
import { fileApi } from '@/api/file'

export default defineComponent({
  name: 'VideoListView',
  components: {
    PlusOutlined,
    SearchOutlined
  },
  setup() {
    const loading = ref(false)
    const videoList = ref([])
    
    // 搜索表单
    const searchForm = reactive({
      status: undefined
    })
    
    // 分页配置
    const pagination = reactive({
      current: 1,
      pageSize: 10,
      total: 0,
      showSizeChanger: true,
      showQuickJumper: true,
      showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条，共 ${total} 条`
    })
    
    // 表格列配置
    const columns = [
      {
        title: 'ID',
        dataIndex: 'id',
        key: 'id',
        width: 80
      },
      {
        title: '封面',
        dataIndex: ['cover_image', 'thumbnail_url'],
        key: 'cover_image',
        width: 100
      },
      {
        title: '视频标题',
        dataIndex: 'title',
        key: 'title',
        ellipsis: true,
        width: 200
      },
      {
        title: '描述',
        dataIndex: 'description',
        key: 'description',
        ellipsis: true,
        width: 300
      },
      {
        title: '文件大小',
        dataIndex: 'file_size',
        key: 'file_size',
        width: 100
      },
      {
        title: '状态',
        dataIndex: 'status',
        key: 'status',
        width: 120
      },
      {
        title: '审核结果',
        dataIndex: 'ai_review_result',
        key: 'ai_review_result',
        width: 120
      },
      {
        title: '创建时间',
        dataIndex: 'created_at',
        key: 'created_at',
        width: 180
      },
      {
        title: '操作',
        key: 'action',
        width: 220,
        fixed: 'right'
      }
    ]
    

    
    // 获取视频列表
    const fetchVideoList = async () => {
      loading.value = true
      try {
        const requestData = {
          page: pagination.current,
          per_page: pagination.pageSize,
          status: searchForm.status || undefined
        }
        
        const response = await videoApi.getList(requestData)
        
        if (response && response.data) {
          videoList.value = response.data.videos || []
          // 根据mock数据结构调整分页信息
          if (response.data.pagination) {
            pagination.total = response.data.pagination.total || 0
            pagination.current = response.data.pagination.current_page || 1
            pagination.pageSize = response.data.pagination.per_page || 10
          } else {
            pagination.total = response.data.total || 0
          }
        } else {
          videoList.value = []
          pagination.total = 0
        }
      } catch (error) {
        console.error('获取视频列表失败:', error)
        const errorMessage = error.response?.data?.message || error.message || '获取视频列表失败'
        message.error(errorMessage)
        videoList.value = []
        pagination.total = 0
      } finally {
        loading.value = false
      }
    }
    
    // 搜索
    const handleSearch = () => {
      pagination.current = 1
      fetchVideoList()
    }
    
    // 重置搜索
    const handleReset = () => {
      searchForm.status = undefined
      pagination.current = 1
      fetchVideoList()
    }
    
    // 表格变化处理
    const handleTableChange = (pag) => {
      pagination.current = pag.current
      pagination.pageSize = pag.pageSize
      fetchVideoList()
    }
    
    // 上传视频相关状态
    const uploadModalVisible = ref(false)
    const uploadLoading = ref(false)
    const videoFileUploading = ref(false)
    const coverFileUploading = ref(false)
    const uploadForm = reactive({
      title: '',
      description: '',
      video_file: '', // 存储file_id
      cover_file: '', // 存储file_id
      upload_source: 'admin',
      video_file_name: '', // 显示文件名
      cover_file_name: '' // 显示文件名
    })
    
    // 审核相关状态
     const reviewModalVisible = ref(false)
     const reviewLoading = ref(false)
     const currentReviewVideo = ref(null)
     const reviewForm = reactive({
       status: 'approve',
       reason: ''
     })
    
    // 上传视频
    const handleUpload = () => {
      uploadModalVisible.value = true
    }
    
    // 处理视频文件选择
    const handleVideoFileChange = async (file) => {
      videoFileUploading.value = true
      try {
        // 构建FormData
        const formData = new FormData()
        formData.append('file', file)
        formData.append('directory', 'uploads') // 指定上传目录
        
        const response = await fileApi.upload(formData)
        
        if (response && response.code === 200) {
          uploadForm.video_file = response.data.file_id
          uploadForm.video_file_name = file.name
          message.success('视频文件上传成功')
        } else {
          message.error(response?.message || '视频文件上传失败')
        }
      } catch (error) {
        console.error('视频文件上传失败:', error)
        const errorMessage = error.response?.data?.message || error.message || '视频文件上传失败'
        message.error(errorMessage)
      } finally {
        videoFileUploading.value = false
      }
      return false // 阻止自动上传
    }
    
    // 处理封面文件选择
    const handleCoverFileChange = async (file) => {
      coverFileUploading.value = true
      try {
        // 构建FormData
        const formData = new FormData()
        formData.append('file', file)
        formData.append('directory', 'uploads') // 指定上传目录
        
        const response = await fileApi.upload(formData)
        
        if (response && response.code === 200) {
          uploadForm.cover_file = response.data.file_id
          uploadForm.cover_file_name = file.name
          message.success('封面图片上传成功')
        } else {
          message.error(response?.message || '封面图片上传失败')
        }
      } catch (error) {
        console.error('封面图片上传失败:', error)
        const errorMessage = error.response?.data?.message || error.message || '封面图片上传失败'
        message.error(errorMessage)
      } finally {
        coverFileUploading.value = false
      }
      return false // 阻止自动上传
    }
    
    // 处理视频文件选择事件
    const handleVideoFileSelect = (info) => {
      if (info.file.status === 'uploading') {
        videoFileUploading.value = true
      }
    }
    
    // 处理封面文件选择事件
    const handleCoverFileSelect = (info) => {
      if (info.file.status === 'uploading') {
        coverFileUploading.value = true
      }
    }
    
    // 上传提交
    const handleUploadSubmit = async () => {
      // 表单验证
      if (!uploadForm.title) {
        message.error('请输入视频标题')
        return
      }
      if (!uploadForm.description) {
        message.error('请输入视频描述')
        return
      }
      if (!uploadForm.video_file) {
        message.error('请选择视频文件')
        return
      }
      if (!uploadForm.cover_file) {
        message.error('请选择封面图片')
        return
      }
      
      uploadLoading.value = true
      try {
        // 构建FormData，使用file_id
        const formData = new FormData()
        formData.append('title', uploadForm.title)
        formData.append('description', uploadForm.description)
        formData.append('video_file_id', uploadForm.video_file) // 现在是file_id字符串
        formData.append('cover_file_id', uploadForm.cover_file) // 现在是file_id字符串
        formData.append('upload_source', uploadForm.upload_source)
        
        const response = await videoApi.upload(formData)
        
        if (response && response.code === 200) {
          message.success('视频上传成功')
          uploadModalVisible.value = false
          handleUploadCancel() // 清空表单
          fetchVideoList() // 刷新列表
        } else {
          message.error(response?.message || '视频上传失败')
        }
      } catch (error) {
        console.error('视频上传失败:', error)
        const errorMessage = error.response?.data?.message || error.message || '视频上传失败'
        message.error(errorMessage)
      } finally {
        uploadLoading.value = false
      }
    }
    
    // 上传取消
    const handleUploadCancel = () => {
      uploadModalVisible.value = false
      uploadForm.title = ''
      uploadForm.description = ''
      uploadForm.video_file = ''
      uploadForm.cover_file = ''
      uploadForm.video_file_name = ''
      uploadForm.cover_file_name = ''
      uploadForm.upload_source = 'admin'
    }
    
    // 编辑视频相关状态
    const editModalVisible = ref(false)
    const editLoading = ref(false)
    const editCoverFileUploading = ref(false)
    const editForm = reactive({
      id: null,
      title: '',
      description: '',
      cover_file: '', // 存储新上传的file_id
      cover_file_name: '', // 显示新上传的文件名
      current_cover_url: '' // 当前封面URL
    })
    
    // 编辑视频
    const handleEdit = (record) => {
      editForm.id = record.id
      editForm.title = record.title
      editForm.description = record.description
      editForm.cover_file = ''
      editForm.cover_file_name = ''
      editForm.current_cover_url = record.cover_image?.thumbnail_url || record.cover_image?.oss_url || ''
      editModalVisible.value = true
    }
    
    // 编辑提交
    const handleEditSubmit = async () => {
      editLoading.value = true
      try {
        // 构建更新数据，只在有新封面时传递cover_file_id
        const updateData = {
          title: editForm.title,
          description: editForm.description
        }
        
        // 只有上传了新封面才添加cover_file_id字段
        if (editForm.cover_file) {
          updateData.cover_file_id = editForm.cover_file
        }
        
        const response = await videoApi.update(editForm.id, updateData)
        
        if (response && response.code === 200) {
          message.success('视频更新成功')
          editModalVisible.value = false
          fetchVideoList() // 刷新列表
        } else {
          message.error(response?.message || '视频更新失败')
        }
      } catch (error) {
        console.error('视频更新失败:', error)
        const errorMessage = error.response?.data?.message || error.message || '视频更新失败'
        message.error(errorMessage)
      } finally {
        editLoading.value = false
      }
    }
    
    // 处理编辑封面文件选择
    const handleEditCoverFileChange = async (file) => {
      editCoverFileUploading.value = true
      try {
        // 构建FormData
        const formData = new FormData()
        formData.append('file', file)
        formData.append('directory', 'uploads') // 指定上传目录
        
        const response = await fileApi.upload(formData)
        
        if (response && response.code === 200) {
          editForm.cover_file = response.data.file_id
          editForm.cover_file_name = file.name
          message.success('封面图片上传成功')
        } else {
          message.error(response?.message || '封面图片上传失败')
        }
      } catch (error) {
        console.error('封面图片上传失败:', error)
        const errorMessage = error.response?.data?.message || error.message || '封面图片上传失败'
        message.error(errorMessage)
      } finally {
        editCoverFileUploading.value = false
      }
      return false // 阻止自动上传
    }
    
    // 处理编辑封面文件选择事件
    const handleEditCoverFileSelect = (info) => {
      if (info.file.status === 'uploading') {
        editCoverFileUploading.value = true
      }
    }
    
    // 编辑取消
    const handleEditCancel = () => {
      editModalVisible.value = false
      editForm.id = null
      editForm.title = ''
      editForm.description = ''
      editForm.cover_file = ''
      editForm.cover_file_name = ''
      editForm.current_cover_url = ''
    }
    
    // 视频详情相关状态
    const detailModalVisible = ref(false)
    const detailLoading = ref(false)
    const videoDetail = ref({})
    
    // 查看视频
    const handleView = async (record) => {
      detailModalVisible.value = true
      detailLoading.value = true
      
      try {
        const response = await videoApi.getDetail(record.id)
        if (response && response.data) {
          videoDetail.value = response.data
        } else {
          videoDetail.value = {}
          message.error('获取视频详情失败')
        }
      } catch (error) {
        console.error('获取视频详情失败:', error)
        const errorMessage = error.response?.data?.message || error.message || '获取视频详情失败'
        message.error(errorMessage)
        videoDetail.value = {}
      } finally {
        detailLoading.value = false
      }
    }
    
    // 关闭详情弹窗
    const handleDetailModalClose = () => {
      detailModalVisible.value = false
      videoDetail.value = {}
    }
    
    // 详情表格列配置
    const detailColumns = [
      {
        title: '字段',
        dataIndex: 'field',
        key: 'field',
        width: 150,
        align: 'right'
      },
      {
        title: '值',
        dataIndex: 'value',
        key: 'value'
      }
    ]
    
    // 详情表格数据
    const detailTableData = computed(() => {
      if (!videoDetail.value || Object.keys(videoDetail.value).length === 0) {
        return []
      }
      
      const detail = videoDetail.value
      const aiResult = detail.ai_review_result
      
      const data = [
        { key: 'id', field: 'ID', value: detail.id || '-' },
        { key: 'title', field: '标题', value: detail.title || '-' },
        { key: 'description', field: '描述', value: detail.description || '-' },
        { key: 'file_id', field: '文件ID', value: detail.file_id || '-' },
        { key: 'cover_image_id', field: '封面图片ID', value: detail.cover_image_id || '-' },
        { key: 'file_size', field: '文件大小', value: formatFileSize(detail.file_size) },
        { key: 'duration', field: '时长', value: formatDuration(detail.duration) },
        { key: 'resolution', field: '分辨率', value: detail.resolution || '-' },
        { key: 'upload_source', field: '上传来源', value: detail.upload_source || '-' },
        { key: 'status', field: '状态', value: getStatusText(detail) },
        { key: 'view_count', field: '观看次数', value: detail.view_count || 0 },
        { key: 'like_count', field: '点赞次数', value: detail.like_count || 0 },
        { key: 'is_featured', field: '是否精选', value: detail.is_featured ? '是' : '否' },
        { key: 'is_active', field: '是否激活', value: detail.is_active ? '是' : '否' },
        { key: 'published_at', field: '发布时间', value: formatDate(detail.published_at) },
        { key: 'created_at', field: '创建时间', value: formatDate(detail.created_at) },
        { key: 'updated_at', field: '更新时间', value: formatDate(detail.updated_at) },
        { key: 'author_nickname', field: '作者昵称', value: detail.author_nickname || '-' },
        { key: 'author_avatar_id', field: '作者头像ID', value: detail.author_avatar_id || '-' },
        { key: 'reject_reason', field: '拒绝原因', value: detail.reject_reason || '-' }
      ]
      
      // AI审核相关信息
      if (aiResult) {
        data.push(
          { key: 'ai_approved', field: 'AI审核结果', value: aiResult.is_approved ? '通过' : '未通过' },
          { key: 'ai_status', field: 'AI审核状态', value: aiResult.status || '-' },
          { key: 'ai_confidence', field: 'AI置信度', value: aiResult.confidence ? `${aiResult.confidence}%` : '-' },
          { key: 'ai_review_time', field: 'AI审核时间', value: aiResult.review_time || '-' }
        )
        
        // AI审核详细结果
        if (aiResult.audit_result) {
          const auditResult = aiResult.audit_result
          if (auditResult.Porn) {
            data.push({ key: 'porn_check', field: '色情检测', value: `${auditResult.Porn.Suggestion} (${auditResult.Porn.Confidence}%)` })
          }
          if (auditResult.Terrorism) {
            data.push({ key: 'terrorism_check', field: '暴恐检测', value: `${auditResult.Terrorism.Suggestion} (${auditResult.Terrorism.Confidence}%)` })
          }
          if (auditResult.Politics) {
            data.push({ key: 'politics_check', field: '政治检测', value: `${auditResult.Politics.Suggestion} (${auditResult.Politics.Confidence}%)` })
          }
          if (auditResult.Ad) {
            data.push({ key: 'ad_check', field: '广告检测', value: `${auditResult.Ad.Suggestion} (${auditResult.Ad.Confidence}%)` })
          }
        }
        
        // 拒绝原因
        if (aiResult.reject_reasons && aiResult.reject_reasons.length > 0) {
          data.push({ key: 'ai_reject_reasons', field: 'AI拒绝原因', value: aiResult.reject_reasons.join(', ') })
        }
      }
      
      return data
    })
    
    // 删除视频
    const handleDelete = async (id) => {
      try {
        await videoApi.delete(id)
        message.success('删除成功')
        // 重新加载列表
        fetchVideoList()
      } catch (error) {
        console.error('删除视频失败:', error)
        const errorMessage = error.response?.data?.message || error.message || '删除失败'
        message.error(errorMessage)
      }
    }
    
    // 审核视频
    const handleReview = (record) => {
      currentReviewVideo.value = record
      reviewForm.status = 'approved'
      reviewForm.reason = ''
      reviewModalVisible.value = true
    }
    
    // 提交审核
    const handleReviewSubmit = async () => {
      if (reviewForm.status === 'rejected' && !reviewForm.reason.trim()) {
        message.error('审核拒绝时必须填写原因')
        return
      }
      
      reviewLoading.value = true
      try {
        const data = {
          action: reviewForm.status,
          reason: reviewForm.reason || undefined
        }
        
        await videoApi.review(currentReviewVideo.value.id, data)
        message.success('审核成功')
        reviewModalVisible.value = false
        // 重新加载列表
        fetchVideoList()
      } catch (error) {
        console.error('审核失败:', error)
        const errorMessage = error.response?.data?.message || error.message || '审核失败'
        message.error(errorMessage)
      } finally {
        reviewLoading.value = false
      }
    }
    
    // 取消审核
    const handleReviewCancel = () => {
      reviewModalVisible.value = false
      currentReviewVideo.value = null
      reviewForm.status = 'approved'
      reviewForm.reason = ''
    }
    
    // 发布视频
    const handlePublish = async (record) => {
      try {
        const response = await videoApi.publish(record.id)
        if (response && response.code === 200) {
          message.success('视频发布成功')
          fetchVideoList() // 刷新列表
        } else {
          message.error(response?.message || '视频发布失败')
        }
      } catch (error) {
        console.error('发布视频失败:', error)
        const errorMessage = error.response?.data?.message || error.message || '发布失败'
        message.error(errorMessage)
      }
    }
    
    // 下架视频
    const handleUnpublish = async (record) => {
      try {
        const response = await videoApi.unpublish(record.id)
        if (response && response.code === 200) {
          message.success('视频下架成功')
          fetchVideoList() // 刷新列表
        } else {
          message.error(response?.message || '视频下架失败')
        }
      } catch (error) {
        console.error('下架视频失败:', error)
        const errorMessage = error.response?.data?.message || error.message || '下架失败'
        message.error(errorMessage)
      }
    }
    
    // 获取状态颜色
     const getStatusColor = (status) => {
       const statusColors = {
         'pending': 'orange',
         'ai_reviewing': 'cyan',
         'ai_approved': 'green',
         'ai_rejected': 'red',
         'manual_reviewing': 'blue',
         'approved': 'green',
         'rejected': 'red',
         'draft': 'orange',
         'published': 'green',
         'archived': 'gray'
       }
       return statusColors[status] || 'default'
     }
     
     // 获取状态文本
    const getStatusText = (record) => {
      const status = record.status || record
      const isActive = record.is_active
      
      // 当状态为approved且is_active为true时，显示为已发布
      if (status === 'approved' && isActive === true) {
        return '已发布'
      }
      
      const statusTexts = {
        'pending': '待审核',
        'ai_reviewing': 'AI审核中',
        'ai_approved': 'AI审核通过',
        'ai_rejected': 'AI审核拒绝',
        'manual_reviewing': '人工审核中',
        'approved': '审核通过',
        'rejected': '审核拒绝',
        'draft': '草稿',
        'published': '已发布',
        'archived': '已归档'
      }
      return statusTexts[status] || status || '未知'
    }
    
    // 格式化时长
    const formatDuration = (seconds) => {
      if (!seconds) return '-'
      const minutes = Math.floor(seconds / 60)
      const remainingSeconds = seconds % 60
      return `${minutes}:${remainingSeconds.toString().padStart(2, '0')}`
    }
    
    // 格式化文件大小
    const formatFileSize = (bytes) => {
      if (!bytes) return '-'
      const sizes = ['B', 'KB', 'MB', 'GB']
      const i = Math.floor(Math.log(bytes) / Math.log(1024))
      return Math.round(bytes / Math.pow(1024, i) * 100) / 100 + ' ' + sizes[i]
    }
    
    // 格式化日期
    const formatDate = (dateString) => {
      if (!dateString) return '-'
      return new Date(dateString).toLocaleString('zh-CN')
    }
    
    // 组件挂载时获取数据
    onMounted(() => {
      fetchVideoList()
    })
    
    return {
      loading,
      videoList,
      searchForm,
      pagination,
      columns,
      handleSearch,
      handleReset,
      handleTableChange,
      handleUpload,
      handleUploadSubmit,
      handleUploadCancel,
      handleVideoFileChange,
      handleCoverFileChange,
      handleVideoFileSelect,
      handleCoverFileSelect,
      uploadModalVisible,
      uploadLoading,
      uploadForm,
      handleEdit,
      handleView,
      handleDelete,
      handleReview,
      handleReviewSubmit,
      handleReviewCancel,
      reviewModalVisible,
      reviewLoading,
      currentReviewVideo,
      reviewForm,
      getStatusColor,
      getStatusText,
      formatDuration,
      formatFileSize,
      formatDate,
      detailModalVisible,
      detailLoading,
      videoDetail,
      handleDetailModalClose,
      detailColumns,
      detailTableData,
      editModalVisible,
      editLoading,
      editForm,
      handleEditSubmit,
      handleEditCancel,
      handlePublish,
      handleUnpublish,
      videoFileUploading,
      coverFileUploading,
      editCoverFileUploading,
      handleEditCoverFileChange,
      handleEditCoverFileSelect
    }
  }
})
</script>

<style scoped>
.video-list-container {
  padding: 20px;
  background: #ffffff;
  min-height: 100vh;
}

.search-card {
  margin-bottom: 16px;
  box-shadow: none;
  border: 1px solid #e8e8e8;
  border-radius: 6px;
}

.video-table {
  background: white;
  border-radius: 6px;
  box-shadow: none;
  border: 1px solid #e8e8e8;
}

.video-table :deep(.ant-table) {
  table-layout: fixed;
}

.video-table :deep(.ant-table-tbody > tr > td) {
  vertical-align: middle;
  height: 50px;
  padding: 12px 16px !important;
  border-bottom: 1px solid #f0f0f0;
}

.video-table :deep(.ant-table-thead > tr > th) {
  background: #fafafa;
  font-weight: 600;
  height: 48px;
  padding: 12px 16px !important;
  border-bottom: 1px solid #e8e8e8;
}

.video-table :deep(.ant-table-tbody > tr) {
  transition: none;
}

.video-table :deep(.ant-table-tbody > tr:hover > td) {
  background-color: #f5f5f5 !important;
}

.video-cover {
  width: 80px;
  height: 60px;
  object-fit: cover;
  border-radius: 4px;
  border: 1px solid #e8e8e8;
  display: block;
  cursor: pointer;
}

.status-tag {
  font-weight: 500;
}

.action-buttons .ant-btn {
  margin-right: 8px;
  padding: 4px 12px;
  font-size: 12px;
  height: 28px;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  background: #ffffff;
  color: #000000;
}

.action-buttons .ant-btn:last-child {
  margin-right: 0;
}

.action-buttons .ant-btn[danger] {
  background: #ff4d4f;
  color: #ffffff;
  border-color: #ff4d4f;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding: 16px 0;
  border-bottom: 1px solid #e8e8e8;
}

.page-header h2 {
  margin: 0;
  color: #000000;
  font-size: 20px;
  font-weight: 600;
}

.add-button {
  box-shadow: none;
  border: 1px solid #1890ff;
  background: #1890ff;
  color: #ffffff;
  border-radius: 4px;
}

.search-form {
  padding: 16px;
}

.table-container {
  overflow-x: auto;
  position: relative;
}

.table-container :deep(.ant-spin-container) {
  min-height: 400px;
}

/* 视频详情样式 */
.video-detail-content {
  max-height: 70vh;
  overflow-y: auto;
}

.detail-section {
  margin-bottom: 24px;
  padding: 16px;
  background: #fafafa;
  border-radius: 6px;
  border: 1px solid #e8e8e8;
}

.section-title {
  margin: 0 0 16px 0;
  font-size: 16px;
  font-weight: 600;
  color: #262626;
  border-bottom: 1px solid #d9d9d9;
  padding-bottom: 8px;
}

.subsection-title {
  margin: 16px 0 12px 0;
  font-size: 14px;
  font-weight: 500;
  color: #595959;
}

.detail-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 12px 24px;
}

.detail-item {
  display: flex;
  align-items: flex-start;
  padding: 8px 0;
}

.detail-item.full-width {
  grid-column: 1 / -1;
}

.detail-item .label {
  min-width: 100px;
  font-weight: 500;
  color: #595959;
  margin-right: 8px;
  flex-shrink: 0;
}

.detail-item .value {
  color: #262626;
  word-break: break-all;
  flex: 1;
}

.audit-details {
  margin-top: 16px;
  padding-top: 16px;
  border-top: 1px solid #e8e8e8;
}

.reject-reasons {
  margin-top: 16px;
  padding-top: 16px;
  border-top: 1px solid #e8e8e8;
}

/* 媒体预览样式 */
.media-preview {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.media-item {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.media-title {
  margin: 0 0 12px 0;
  font-size: 14px;
  font-weight: 500;
  color: #595959;
  align-self: flex-start;
}

.cover-preview {
  max-width: 100%;
  max-height: 300px;
  width: auto;
  height: auto;
  border-radius: 8px;
  border: 1px solid #e8e8e8;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  object-fit: contain;
}

.video-preview {
  max-width: 100%;
  max-height: 400px;
  width: auto;
  height: auto;
  border-radius: 8px;
  border: 1px solid #e8e8e8;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

/* 审核弹窗样式 */
.review-video-info {
  margin-bottom: 24px;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 6px;
  border: 1px solid #e8e8e8;
}

.review-video-info h4 {
  margin: 0 0 12px 0;
  color: #262626;
  font-size: 16px;
  font-weight: 600;
}

.review-video-info p {
  margin: 8px 0;
  color: #595959;
  font-size: 14px;
}

.review-video-info strong {
  color: #262626;
  font-weight: 500;
}

.video-preview:focus {
  outline: 2px solid #1890ff;
  outline-offset: 2px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .video-list-container {
    padding: 16px;
  }
  
  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }
  
  .search-form .ant-form-item {
    margin-bottom: 12px;
  }
  
  .detail-grid {
    grid-template-columns: 1fr;
    gap: 8px;
  }
  
  .detail-item .label {
    min-width: 80px;
  }
  
  .cover-preview {
    max-height: 200px;
  }
  
  .video-preview {
    max-height: 250px;
  }
}
</style>